<template>
  <div class="main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="card-title">客户管理</div>
          <div class="card-tools">
            <el-button type="primary" @click="handleAdd">新增客户</el-button>
            <el-button 
              v-if="multipleSelection.length > 0" 
              type="danger" 
              @click="handleBatchDelete"
              class="ml-2"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area mb-4">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入客户姓名/手机号搜索"
          prefix-icon="Search"
          @keydown.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" class="search-button">搜索</el-button>
            <el-button @click="handleReset" class="reset-button">清空</el-button>
          </template>
        </el-input>
      </div>

      <!-- 表格区域 -->
      <el-table
        ref="multipleTableRef"
        v-loading="loading"
        :data="customerList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="序号" width="80" type="index" align="center">
          <template #default="scope">
            {{ (pagination.page - 1) * pagination.limit + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" min-width="120" align="center" />
        <el-table-column prop="gender" label="性别" min-width="80" align="center">
          <template #default="scope">
            {{ scope.row.gender === 0 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" min-width="150" align="center" />
        <el-table-column prop="status" label="状态" min-width="120" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 2 ? 'success' : scope.row.status === 1 ? 'primary' : 'info'" 
              size="small"
            >
              {{ scope.row.status === 0 ? '潜在客户' : scope.row.status === 1 ? '意向客户' : '签约客户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="intention" label="租赁意向" min-width="120" align="center">
          <template #default="scope">
            {{ getIntentionText(scope.row.intention) }}
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="录入时间" min-width="180" align="center" />
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)" size="small">编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row)" size="small" danger>删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination mt-4 flex justify-end items-center">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑客户' : '新增客户'"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择">
            <el-option label="潜在客户" :value="0" />
            <el-option label="意向客户" :value="1" />
            <el-option label="签约客户" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁意向" prop="intention">
          <el-select v-model="formData.intention" placeholder="请选择">
            <el-option label="车位" :value="0" />
            <el-option label="广告费" :value="1" />
            <el-option label="房屋" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            placeholder="请输入备注信息" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { getCustomerList, addCustomer, updateCustomer, deleteCustomer, getCustomerById, deleteCustomerBatch } from '@/api/customer';

// 客户类型定义
interface Customer {
  id: number;
  name: string;
  gender: number; // 性别：0代表男，1代表女
  phone: string;
  email?: string;
  address?: string;
  status: number; // 客户状态：0潜在客户,1意向客户,2签约客户
  intention: number; // 租赁意向：0车位，1广告费，2房屋
  remark: string;
  admin_id?: number; // 修改为number类型，与后端返回的数据类型匹配
  createTime?: string; // 改为createTime，与后端字段一致
  tenantId: number;
}

// 分页相关数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
});

// 搜索表单数据
const searchForm = reactive({
  keyword: ''
});

// 客户列表数据
const customerList = ref<Customer[]>([]);

// 表格加载状态
const loading = ref(false);

// 对话框相关数据
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const formData = reactive<Partial<Customer>>({
  gender: 0,
  status: 1, // 默认为意向客户
  intention: 0,
  email: ''
});
let currentCustomerId = 0;

// 多选相关数据
const multipleTableRef = ref();
const multipleSelection = ref<Customer[]>([]);

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: false },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  intention: [{ required: true, message: '请选择租赁意向', trigger: 'change' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
});

// 格式化日期函数（保留以备他用）
// const formatDate = (dateString?: string) => {
//   if (!dateString) return '';
//   const date = new Date(dateString);
//   return date.toLocaleDateString('zh-CN');
// };

// 获取租赁意向文本
const getIntentionText = (intention: number): string => {
  const intentionMap: Record<number, string> = {
    0: '车位',
    1: '广告费',
    2: '房屋'
  };
  return intentionMap[intention] || '';
};

// 获取客户列表
const fetchCustomerList = async () => {
  try {
    loading.value = true;
    console.log('开始获取客户列表，参数:', {page: pagination.page, limit: pagination.limit, query: searchForm.keyword});
    
    // 构建查询参数
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      query: searchForm.keyword
    };
    
    // 调用API获取客户列表
    const res = await getCustomerList(params);
    console.log('获取客户列表结果:', res);
    
    // 检查数据结构并适配
    if (res && res.code === 0) {
      let customerData: Customer[] = [];
      
      // 检查数据结构并适配
      if (res.data && res.data.records && Array.isArray(res.data.records)) {
        // 处理后端返回的records格式数据
        customerData = res.data.records;
        pagination.total = res.data.total || res.data.totalCount || 0;
        console.log('获取到客户数据(records)，数量:', customerData.length);
      } else if (res.data && res.data.list && Array.isArray(res.data.list)) {
        // 处理list格式数据
        customerData = res.data.list;
        pagination.total = res.data.total || 0;
        console.log('获取到客户数据(list)，数量:', customerData.length);
      } else if (res.data && Array.isArray(res.data)) {
        // 适配数据直接是数组的情况
        customerData = res.data;
        pagination.total = res.data.length;
        console.log('获取到客户数据(数组)，数量:', customerData.length);
      } else {
        // 处理其他可能的数据结构
        console.warn('客户列表数据结构与预期不符:', res.data);
        customerList.value = [];
        pagination.total = 0;
      }
      
      // 设置客户列表数据
      customerList.value = customerData;
    } else {
      ElMessage.error(res?.message || '获取客户列表失败');
      customerList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取客户列表失败:', error);
    ElMessage.error('获取客户列表失败');
    customerList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索功能
const handleSearch = () => {
  pagination.page = 1;
  fetchCustomerList();
};

// 重置搜索
const handleReset = () => {
  searchForm.keyword = '';
  pagination.page = 1;
  fetchCustomerList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchCustomerList();
};

// 当前页码改变
const handleCurrentChange = (current: number) => {
  pagination.page = current;
  fetchCustomerList();
};

// 打开新增客户对话框
const handleAdd = () => {
  isEdit.value = false;
  // 重置表单数据
  Object.assign(formData, {
    name: '',
    gender: 0,
    phone: '',
    email: '',
    status: 1, // 默认为意向客户
    intention: 0,
    remark: '',
    admin_id: 'admin', // 假设当前操作用户
    tenantId: 1 // 假设默认租户ID为1
  });
  dialogVisible.value = true;
};

// 打开编辑客户对话框
const handleEdit = async (row: Customer) => {
  isEdit.value = true;
  currentCustomerId = row.id;
  
  try {
    console.log('获取客户详情，id:', row.id);
    const res = await getCustomerById(row.id);
    console.log('获取客户详情结果:', res);
    
    if (res && res.code === 0 && res.data) {
      // 确保数据格式正确
      const customerData = {
        ...res.data,
        // 确保gender字段存在且为数字
        gender: res.data.gender !== undefined ? Number(res.data.gender) : 0,
        // 确保intention字段存在且为数字
        intention: res.data.intention !== undefined ? Number(res.data.intention) : 0,
        // 确保status字段存在且为数字
        status: res.data.status !== undefined ? Number(res.data.status) : 1,
        // 确保admin_id字段存在且为数字
        admin_id: res.data.admin_id !== undefined ? Number(res.data.admin_id) : undefined
      };
      Object.assign(formData, customerData);
      dialogVisible.value = true;
    } else {
      ElMessage.error(res?.message || '获取客户详情失败');
    }
  } catch (error) {
    console.error('获取客户详情失败:', error);
    ElMessage.error('获取客户详情失败');
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    if (isEdit.value) {
      // 修改客户
      const res = await updateCustomer({
        ...formData,
        id: currentCustomerId,
        tenantId: formData.tenantId || 1,
        // 确保字段名正确，移除旧的字段名
        gender: Number(formData.gender) || 0,
        intention: Number(formData.intention) || 0,
        status: Number(formData.status) || 1,
        admin_id: formData.admin_id || 'admin'
      } as any);
      if (res.code === 0) {
        ElMessage.success('修改成功');
        dialogVisible.value = false;
        fetchCustomerList();
      } else {
        ElMessage.error(res.message || '修改失败');
      }
    } else {
      // 新增客户
      const res = await addCustomer({
        ...formData,
        tenantId: 1, // 假设默认租户ID为1
        // 确保字段名正确，移除旧的字段名
        gender: Number(formData.gender) || 0,
        intention: Number(formData.intention) || 0,
        status: Number(formData.status) || 1,
        admin_id: formData.admin_id || 'admin'
      } as any);
      if (res.code === 0) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        fetchCustomerList();
      } else {
        ElMessage.error(res.message || '新增失败');
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 删除客户
const handleDelete = (row: Customer) => {
  ElMessageBox.confirm('确定要删除这个客户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteCustomer(row.id);
      if (res.code === 0) {
        ElMessage.success('删除成功');
        fetchCustomerList(); // 重新获取客户列表
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除客户失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 多选处理函数
const handleSelectionChange = (val: Customer[]) => {
  multipleSelection.value = val;
};

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的客户吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 使用批量删除API
      const ids = multipleSelection.value.map(item => item.id);
      const res = await deleteCustomerBatch(ids);
      
      if (res.code === 0) {
        ElMessage.success(`成功删除${ids.length}个客户`);
        fetchCustomerList();
      } else {
        ElMessage.error(res.message || '批量删除失败');
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 初始加载数据
onMounted(() => {
  fetchCustomerList();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
}

.search-area {
  margin-bottom: 16px;
}

.search-button {
  margin-right: 8px;
}

.reset-button {
  color: #606266;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>